#!/bin/bash
set -xeuo pipefail
set -o errexit

#建立测试数据和索引
#
# USER="-u elastic-admin:elastic-password"
USER=""

echo "reset index template"

# 索引不保留冗余副本
# curl ${USER} -H "Content-Type: application/json" -XPUT 'http://localhost:9200/_all/_settings?preserve_existing=true' -d '{ "index.number_of_replicas" : "0" }'
curl ${USER} -XPUT 'http://localhost:9200/_settings' -H 'Content-Type: application/json' -d '{ "settings": {	 "number_of_replicas" : 0  }}'

echo ""
curl ${USER} -X DELETE "localhost:9200/aggt"
curl ${USER} -X DELETE "localhost:9200/aggt_t"
curl ${USER} -X DELETE "localhost:9200/_transform/aggt"

echo "create index..."
curl ${USER} -XPUT "localhost:9200/aggt" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "index": {
      "number_of_replicas": "0"
    }
  },
  "mappings": {
      "properties": {
        "clientip": {
          "type": "ip"
        },          
        "port": {
          "type": "integer"
        },

        "sql":{
          "type": "keyword"
        },
        "tm": {
          "type": "date",
          "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_second"
        }
      }
    }
}
'
echo "load data..."
curl ${USER} -v -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/aggt/_bulk?pretty' --data-binary @dbg.json

#NOTE: kibana UI上操作时，需要对aggt建立索引模式才能继续操作，使用API时不需要这个
echo "transforms..."
curl ${USER} -X PUT "localhost:9200/_transform/aggt?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": [
      "aggt"
    ]
  },
  "dest" : { 
    "index" : "aggt_t"
  },
  "pivot": {
    "group_by": {
      "clientip": {
        "terms": {
          "field": "clientip"
        }
      },
      "port": {
        "histogram": {
          "field": "port",
          "interval": "1"
        }
      }
    },
    "aggregations": {
      "tm.value_count": {
        "value_count": {
          "field": "tm"
        }
      }
    }
  }
}
'
cat <<EOF
可以2个模式调试，1 Preview方式【部分数据】 2 正式工作方式【全部数据】"
对应在idea中设置断点，然后分别执行 dbd2... dbg3即可
到对应逻辑出会停止，此时可以动态分析代码情况
EOF
